﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace STSdb.General.Mathematics
{
    public static class MathUtils
    {
        private const int SIGN_MASK = ~Int32.MinValue;

        /// <summary>
        /// Returns the number of digits after the decimal point.
        /// </summary>
        public static int GetDigits(decimal value)
        {
            return (Decimal.GetBits(value)[3] & SIGN_MASK) >> 16;
        }

        /// <summary>
        /// Returns the number of digits after the decimal point;
        /// Returns -1, if it is not possible to convert the double value to decimal and back without precision loss.
        /// </summary>
        public static int GetDigits(double value)
        {
            decimal val = (decimal)value;
            double tmp = (double)val;
            if (tmp != value)
                return -1;

            return GetDigits(val);
        }

        /// <summary>
        /// Returns the number of digits after the decimal point;
        /// Returns -1, if it is not possible to convert the float value to decimal and back without precision loss.
        /// </summary>
        public static int GetDigits(float value)
        {
            decimal val = (decimal)value;
            float tmp = (float)val;
            if (tmp != value)
                return -1;

            return GetDigits(val);
        }

        public static ulong Max(params ulong[] values)
        {
            ulong maxValue = values[0];

            for (int i = 1; i < values.Length; i++)
            {
                if (values[i] > maxValue)
                    maxValue = values[i];
            }

            return maxValue;
        }

#if WindowsCE || PocketPC
        public static double Log(double a, double newBase)
        {
            if ((newBase != 1.0) && ((a == 1.0) || ((newBase != 0.0) && !double.IsPositiveInfinity(newBase))))
            {
                return (Math.Log(a) / Math.Log(newBase));
            }

            return double.NaN;
        }
#endif
    }
}
